#!/usr/bin/env python

import json
import restclient
import resource.string.app

from _console import Console

class Uploader(Console):

    def run(self):
        self.greeting(resource.string.app)
        
        self.upload()
        
        self.farewell()

    def upload(self):
        d = (self._args.url, self._args.sequence)
        self.progress('Uploading snapshot to http://%s as %s.jpg ... ' % d)
        
        url = 'http://%s/camera/upload.html?id=%s' % d
        name = '%s.jpg' % self._args.sequence
        image = open(name, 'rb').read()
        files = {'file': {'file': image, 'filename': 'image.jpg'}}
        try:
            responses = restclient.rest_invoke(url, method="POST", files=files,
                                               async=False, resp=True)
            data = json.loads(responses[1])
            result = True if data['success'] else False
            self.success('OK ^_^v\n')
        except:
            result = False
            self.fail('Error >_<\n')
        
        return result